import { EventEmitter } from "events";
import { DirectoryUnit, TinyUnit } from "./tinyUnit";
import { ChildUnit } from "./childTiny";
import { KeeperService, ifKeepKeyUnit } from "./Keeper";
import { getConfig } from "./config";


/**
 * 压缩管理模块
 */
export class CompressMgr extends EventEmitter {
    directoryMgr: DirectoryUnit;

    childPool: Array<ChildUnit> = [];
    startTime: number = 0;
    _callback;
    constructor() {
        super();
    }

    compressStart(src: string, dst: string, callBack?: Function) {
        this._callback = callBack;
        this.directoryMgr = new DirectoryUnit(src, dst, this);
    }


    compressTinyStart() {
        this.startTime = Date.now();
        setInterval(this.update.bind(this), 100);
    }

    totalFileCount = 0;
    totalFinishCount = 0;
    addFile() {
        this.totalFileCount++;
    }

    finishFile(fileName: string, succ: string | boolean) {
        this.totalFinishCount++;
        console.log("压缩结束:", fileName + "-----" + succ + "-----" + this.totalFinishCount, this.totalFileCount);
        this.emit('progress', Math.floor(this.totalFinishCount / this.totalFileCount * 100));
        if (this.totalFinishCount >= this.totalFileCount) {
            KeeperService.freshAllDB().then(() => {
                // process.exit(0);
                this.emit('complete');
            });
        }
    }

    tinycbpool: Array<TinyUnit> = [];
    busy: boolean;
    userKey: ifKeepKeyUnit;

    // qeuryFree: Array<number> = [];
    queryMax = 10;

    update() {
        if (this.busy) return;
        this.next();
    }

    addPool(fn) {
        // if (typeof fn != 'function') return;
        this.tinycbpool.push(fn);
    }

    finish(index: number) {
        // this.qeuryFree.push(index);
        for (var i = 0; i < this.childPool.length; i++) {
            var cp = this.childPool[i];
            if (!cp || cp.pid != index) continue;
            cp.destory();
            this.childPool.splice(i, 1);
            break;
        }
    }

    async next() {
        if (this.childPool.length >= 10 || this.tinycbpool.length == 0 || this.busy) {
            return;
        }

        // 先找一个数量
        if (!this.userKey || this.userKey.count == 0) {
            this.busy = true;
            this.userKey = await KeeperService.getPressKey();
            this.busy = false;
        }

        if (this.tinycbpool.length == 0) return this.next();
        var count = this.userKey.count;
        if (count <= 0) {
            throw ('no count');
        }

        this.userKey.change(count - 1);
        var unit = this.tinycbpool.shift();
        var tm = new Date();
        console.log("压缩开始",tm.toDateString() + ' ' + tm.toTimeString() + '  ' + unit.name + '  ' + unit.md5);
        var cp = new ChildUnit();
        if (cp) {
            cp.tiny(this.userKey.key, unit.buffer, getConfig("retry", 0), getConfig("timeout", 0)).then(({ data, succ, count }: { data: Buffer, succ: boolean, count: number }) => {
                unit.doTinySave(data, succ);
            }).finally(this.finish.bind(this, cp.pid))

            this.childPool.push(cp);
        }
        else {
            this.tinycbpool.push(unit);
        }

    }
}